<template>
  <div>
    <statistic-head :page="page"></statistic-head>
    <el-scrollbar
      wrapClass="scrollbar-wrap"
      style="background-color: white"
      :style="{
        height: scrollHeight,
        // width: scrollWidth
      }"
      ref="scrollbarContainer">
      <div id="home">
        <div style="background-color: white">
          <div class="head">
            <el-row style="padding-bottom: 10px">
              <el-col :span="4" style="padding: 10px">
                <li style="font-size: 15px">
                  当前总能耗：{{totalEC}}度
                </li>
              </el-col>
              <el-col :span="3" style="width:200px;padding: 10px">
                <li style="font-size: 15px">
                  最高能耗：{{maxEC_blcN}} {{maxEC}}度
                </li>
              </el-col>
              <el-col :span="3" style="width:200px;padding: 10px">
                <li style="font-size: 15px">
                  最低能耗：{{minEC_blcN}} {{minEC}}度
                </li>
              </el-col>
            </el-row>
          </div>
          <template>
            <div v-for="item in tableData">
              <div style="width: 50%;float: left">
                <el-row>
                  <template>
                    <ve-pie :data="item.chartData" :data-empty="item.dataEmpty" :events="item.chartEvents"></ve-pie>
                  </template>
                </el-row>
                <el-row>
                  <el-col :span="8" :offset="8">
                    <li style="text-align: center;padding-bottom: 20px">{{item.block}}能耗:{{item.EC}}度</li>
                  </el-col>
                </el-row>
              </div>
            </div>
          </template>
        </div>
      </div>
    </el-scrollbar>
    <detail-dialog
      :showDetailDialog="showDetailDialog"
      :tableData="tableData_detail"
      :maxEc="maxEc"
      :minEc="minEc"
      :avgEc="avgEc"
      @closeModel="closeModel"></detail-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import VeLine from 'v-charts/lib/line.common'
  import VeHistogram from 'v-charts/lib/histogram.common'
  import VePie from 'v-charts/lib/pie.common'
  import VeChart from 'v-charts/lib/chart'
  import 'v-charts/lib/style.css'
  import statisticHead from "./componet/statisticHead"
  import detailDialog from "./componet/detailDialog"
  import Axios from 'axios'

  export default {
    components: {
      VeLine,
      VeHistogram,
      VePie,
      VeChart,
      statisticHead,
      detailDialog
    },

    data() {
      this.extend = {
        'xAxis.0.axisLabel.rotate': 45
      };
      return {
        showDetailDialog: false,
        scrollHeight: '0px',
        chartTypeWeek: 'pie',
        chartSettingsWeek: {type:'pie'},
        startTime: '',
        endTime: '',
        pickerOptions1: {
          disabledDate(time) {
            return time.getTime() >= Date.now() - 8.64e6;
          }
        },
        pickerOptions2: {},
        totalEC: '4396',
        maxEC: '',
        avgEC: '',
        minEC: '',
        maxEC_blcN: '',
        minEC_blcN: '',
        maxEc: '',
        avgEc: '',
        minEc: '',
        radio: 'line',
        page: '默认显示',

        tableData: [],
        tableData_detail: [],

        deviceTypes: [],
        deviceTypeId: '',

        xMonth: {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31},
        yMonth: {1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
      }
    },
    methods:{
      closeModel(){
        this.tableData_detail = []
        this.showDetailDialog = false
      },

      //数据统计
      getData(){
        let self = this
        let date = new Date()
        let i = 5
        let day = date.getDate()
        let month = date.getMonth()
        let year = date.getFullYear()
        if(self.startTime ===''){
          console.log(date) //Thu Oct 22 2020 16:38:57 GMT+0800 (中国标准时间)
          if (day-i <= 0 && month <= 0) {
            self.startTime = (year-1) + '-' + month + '-' + (self.xMonth[month]+day-i)
          } else if (day-i <= 0 && month === 2 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0)) {
            self.startTime = year + '-' + month + '-' + (self.yMonth[month]+day-i)
          } else if (day-i <= 0) {
            self.startTime = year + '-' + month + '-' + (self.xMonth[month]+day-i)
          } else {
            self.startTime = year + '-' + (month+1) + '-' + (day - i)
          }
        }
        Axios.get(this.api+'getECOfAllBlock',{
          headers:{'X-Requested-With':'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          console.log(res.data)
          console.log(res.data.ECOfBlock)
          let obj  = res.data.ECOfBlock
          let ECOfBlock = Object.keys(obj).map(key => {
            return obj[key]
          })
          console.log(ECOfBlock)
          self.totalEC = res.data.total.totalEC
          self.maxEC = res.data.total.maxEC
          self.avgEC = res.data.total.avgEC
          self.minEC = res.data.total.minEC
          self.maxEC_blcN = res.data.total.maxECBlock
          self.minEC_blcN = res.data.total.minECBlock
          ECOfBlock.forEach(item =>{
            let sum = 0
            let table = []
            let isNull = false
            if (item.ECOfType.length === 0) {
              isNull = true
            }else {
              item.ECOfType.forEach(ec => {
                if (ec.electricConsume!== undefined){
                  sum += ec.electricConsume
                }
                table.push({'类型':ec.deviceTypeName,'能耗':ec.electricConsume})
              })
            }
            // if (table)
            self.tableData.push(
              {
                block: item.blockName,
                blockId: item.blockId,
                EC: sum,
                dataEmpty: isNull,
                chartData: {
                  columns: ['类型','能耗'],
                  rows: table
                },
                chartEvents: {
                  click: function (e) {
                    console.log('3333'+e.name)
                    self.getDeviceTypeId(e.name)
                    self.getTableDate(self.startTime,self.deviceTypeId,item.blockId)
                    self.showDetailDialog = true
                  }
                }
              }
            )
          })
          console.log(self.tableData)

          // for (let i = 0;i< ECOfBlock.length;i++){
          //   let sum = 0
          //   self.tableData[i].chartData.columns = ['类型','能耗']
          //   for(let j = 0;j<ECOfBlock[i].ECOfType.length;j++){
          //     sum += ECOfBlock[i].ECOfType[j].electricConsume
          //     self.tableData[i].chartData.rows[j] = {
          //       '类型':ECOfBlock[i].ECOfType[j].deviceTypeName,'能耗':ECOfBlock[i].ECOfType[j].electricConsume
          //     }
          //   }
          //   self.tableData[i].EC = sum
          //   self.tableData[i].blockId = ECOfBlock[i].blockId
          //   self.tableData[i].block = ECOfBlock[i].blockName
          // }
        })
      },
      getTableDate(startTime,type,blockId){
        let self = this
        let date = new Date()
        Axios.get(this.api+'getECOfDevice',{
          params:{
            blockId: blockId,
            deviceTypeId: type,
            startTime: startTime,
            endTime: date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()
          },
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          self.maxEc = res.data.total.maxEC
          self.minEc = res.data.total.minEC
          self.avgEc = res.data.total.avgEC
          res.data.device.forEach(item =>{
            // console.log(item.EC)
            let table = []
            item.ECOfDay.forEach(ec => {
              table.push({'日期':ec.createTime,'能耗':ec.electricConsume})
            })
            self.tableData_detail.push({
              name: item.deviceName,
              num: item.subEquipment,
              type: item.deviceTypeName,
              totalEc: item.EC,
              model: item.brandName+item.modelName,
              ip: item.ipAddress,
              port: item.port,
              id: item.deviceId,
              location: item.zoneName+item.buildingName+item.roomName,
              roomType: item.roomTypeName,
              dept: item.deptName,
              chartData: {
                columns: ['日期','能耗'],
                rows: table
              }
            })
          })
        })
      },
      getDeviceTypes(){
        let self = this
        self.deviceTypes = []
        Axios.get(this.api+'types',{
          headers: {'X-Requested-With': 'XMLHttpRequest'},
          withCredentials: true
        }).then(res => {
          self.deviceTypes = res.data
          console.log(self.deviceTypes)
        })
      },
      getDeviceTypeId(name){
        this.deviceTypes.forEach(type => {
          if (type.name === name){
            this.deviceTypeId = type.id
          }
        })
      }
    },
    mounted(){
      this.scrollHeight = window.innerHeight*0.95 + 'px'
      this.getData()
      this.getDeviceTypes()
    },
    watch:{
      radio(newVal){
        console.log(newVal)
        this.chartSettingsMonth.type = newVal
      }
    }
  }
</script>

<style>
  .el-scrollbar__wrap{
    height: 90%;
    overflow-x: hidden;
  }
  /*.scrollbar-wrap{*/
  /*  overflow-x: hidden;*/
  /*}*/
</style>
